package com.helpdesk.controlador;

import com.helpdesk.entidades.HdDetalleTicket;
import com.helpdesk.controlador.util.JsfUtil;
import com.helpdesk.controlador.util.PaginationHelper;
import com.helpdesk.dao.HdDetalleTicketFacade;
import com.helpdesk.ejb.MBLogin;
import com.helpdesk.entidades.*;
import com.helpdesk.utilidades.EnviarCorreos;

import java.io.Serializable;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;

@ManagedBean(name = "hdDetalleTicketController")
@SessionScoped
public class HdDetalleTicketController implements Serializable {

    private HdDetalleTicket current;
    private HdDetalleTicket detTicket;
    private DataModel items = null;
    private DataModel obs = null;
    private HdTecnicos codTecnico;
    private HdEstados estado;
    private int contTickets;
    private DataModel listAsigna = null;
    @EJB
    private com.helpdesk.dao.HdDetalleTicketFacade ejbFacade;
    @EJB
    private com.helpdesk.dao.HdTicketsFacade tickFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;

    public HdDetalleTicketController() {
    }

    //MORTEZ
    public HdTecnicos getCodTecnico() {
        return codTecnico;
    }

    public void setCodTecnico(HdTecnicos codTecnico) {
        this.codTecnico = codTecnico;
    }

    public int getContTickets() {
        try {

            return ejbFacade.buscarTicketbyEstadoandTecnico(estado.getAbrevEstado(), codTecnico.getCodTecnico());
        } catch (Exception e) {
            return 0;
        }
    }

    public void setContTickets(int contTickets) {
        this.contTickets = contTickets;
    }

    public HdEstados getEstado() {
        return estado;
    }

    public void setEstado(HdEstados estado) {
        this.estado = estado;
    }

    public DataModel getListAsigna() {
        MBLogin log = (MBLogin) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("mBLogin");

        try {
            List<HdDetalleTicket> lista = ejbFacade.listaAsignaTec(log.getCodUsuario());
            listAsigna = new ListDataModel(lista);

        } catch (Exception e) {
            return null;
        }

        return listAsigna;
    }

    public void setListAsigna(DataModel listAsigna) {
        this.listAsigna = listAsigna;
    }

    public HdDetalleTicket getDetTicket() {
        return detTicket;
    }

    public void setDetTicket(HdDetalleTicket detTicket) {
        this.detTicket = detTicket;
    }

    //-------------------
    public HdDetalleTicket getSelected() {
        if (current == null) {
            current = new HdDetalleTicket();
            selectedItemIndex = -1;
        }
        return current;
    }

    private HdDetalleTicketFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (HdDetalleTicket) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new HdDetalleTicket();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("HdDetalleTicketCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (HdDetalleTicket) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String create1(List<HdTecnicos> Ltecnicos, HdTickets ticket) {
        java.util.Date fecha = new Date();
        String ret = "";
        for (HdTecnicos tec : Ltecnicos) {
            try {
                HdDetalleTicket HDti = new HdDetalleTicket();
                HDti.setCodTicket(ticket);
                HDti.setCodTecnico(tec);
                HDti.setFecAsignacion(fecha);
                getFacade().create(HDti);
                JsfUtil.addSuccessMessage("Registro Almacenado con exito");
                ret = "";
            } catch (Exception e) {
                JsfUtil.addErrorMessage(e,
                ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
                return ret = null;
            }
        }
          return ret;
    }
    
    public String create2(HdTecnicos Ltecnicos, HdTickets ticket) {
        java.util.Date fecha = new Date();
        String ret = "";
            try {
                HdDetalleTicket HDti = new HdDetalleTicket();
                ticket.setCodEstado(new HdEstados(3));
                HDti.setCodTicket(ticket);
                HDti.setCodTecnico(Ltecnicos);
                HDti.setFecAsignacion(fecha);
                getFacade().create(HDti);
                JsfUtil.addSuccessMessage("Registro Almacenado con exito");
                //HdTickets tic = (HdTickets) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("hdTicketsController");
                
                ret = "";
            } catch (Exception e) {
                JsfUtil.addErrorMessage(e,
                ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
                return ret = null;
            }
        
          return ret;
    }

    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("HdDetalleTicketUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (HdDetalleTicket) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("HdDetalleTicketDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = HdDetalleTicket.class)
    public static class HdDetalleTicketControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            HdDetalleTicketController controller = (HdDetalleTicketController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "hdDetalleTicketController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof HdDetalleTicket) {
                HdDetalleTicket o = (HdDetalleTicket) object;
                return getStringKey(o.getCodDetTicket());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + HdDetalleTicketController.class.getName());
            }
        }
    }

    public String actionCant() {
        // return "CantTickets2";
        return "";
    }
}
